// dev-server.js
const path = require('path')
const express = require('express')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const glob = require('glob')

// const fs = require('fs')
// const MemoryFs = require('memory-fs')

const webpackConfig = require('./build/webpack.base.conf')
const app = express()
const port = 8080


// 获取指定路径下的入口文件
function getEntries(globPath) {
  const files = glob.sync(globPath)
  const entries = {}

  files.forEach(function(filepath) {
    // 取倒数第二层(view下面的文件夹)做包名
    const split = filepath.split('/')
    const name = split[split.length - 2]
    entries[name] = './' + filepath
  })

  return entries
}

const entries = getEntries('src/views/**/index.js')
webpackConfig.plugins = []

Object.keys(entries).forEach(function(name) {
  // 每个页面生成一个entry，如果需要HotUpdate，在这里修改entry
  webpackConfig.entry[name] = entries[name]
  // 每个页面生成一个html
  const plugin = new HtmlWebpackPlugin({
    // 生成出来的html文件名
    filename: name + '.html',
    // 每个html的模版，这里多个页面使用同一个模版
    template: './src/views/template.html',
    // 自动将引用插入html
    inject: true,
    // 每个html引用的js模块，也可以在这里加上vendor等公用模块
    chunks: [name]
  })
  webpackConfig.plugins.push(plugin)
})

webpackConfig.plugins.push(
  new HtmlWebpackPlugin({
    filename: 'index.html',
    template: 'index.html',
    inject: true
  })
)

// webpack编译器
const compiler = webpack(webpackConfig)

// webpack-dev-server中间件
const devMiddleware = require('webpack-dev-middleware')(compiler, {
  publicPath: webpackConfig.output.publicPath,
  stats: {
    colors: true,
    chunks: false
  }
})

app.use(devMiddleware)


// const mfs = new MemoryFs
// compiler.outputFileSystem = mfs
// 路由
app.get('/:viewname?', function(req, res, next) {
  let viewname = req.params.viewname
  if (viewname === 'favicon.ico') { return }
  viewname = (viewname || 'index') + '.html'

  let filepath = path.join(compiler.outputPath, viewname);
  // 使用webpack提供的outputFileSystem
  compiler.outputFileSystem.readFile(filepath, function(err, result) {
    if (err) {
        // something error
        return next(err);
    }
    res.set('content-type', 'text/html');
    res.send(result);
    res.end();
  });

});

module.exports = app.listen(port, function(err) {
  if (err) {
      // do something
      return;
  }

  console.log('Listening at http://localhost:' + port + '\n')
})




